<template>
  <div>
    <el-form ref="pram" :model="pram" label-width="100px" @submit.native.prevent>
      <el-form-item label="角色名称" prop="roleName" :rules="[{required:true,message:'请填写角色名称', trigger:['blur','change']}]">
        <el-input v-model="pram.roleName" placeholder="身份名称" />
      </el-form-item>
      <el-form-item label="角色级别" prop="level" :rules="[{ required:true,message:'请选择角色级别',trigger:['blur','change'] }]">
        <el-select v-model="pram.level" placeholder="角色级别" clearable style="width: 100%">
          <el-option
            v-for="(item,index) in levelList"
            :key="index"
            :label="item.levelName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="pram.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <!-- <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox> -->
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSubmit('pram')"  v-hasPermi="['admin:system:role:update','admin:system:role:save']">{{ isCreate===0?'确定':'更新' }}</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as roleApi from '@/api/role.js'
import {Debounce} from '@/utils/validate'
export default {
  name: "roleEdit",
  props: {
    //限制类型，并作为一个对象去使用
    isCreate: {
      //0新增 1更新
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: null
    },
  },
  data() {
    return {
      pram: {
        roleName: null,
        rules: '',
        status: 0,
        level:null,
        id: 0
      },
      menuList:[],
      menuExpand: false,
      menuNodeAll: false,
      menuOptions:[],
      menuCheckStrictly: true,
      currentNodeId:[],
      defaultProps: {
        children: "childList",
        label: "name",
      },
      menuIds:[],
      levelList:[],
    }
  },
  mounted() {
    this.initEditData();
    this.getCacheMenu();
    this.handleGetLevelList();
  },
  methods: {
    close() {
      this.$emit('hideEditDialog')
    },

    handleGetLevelList() {
      //roleApi.getCommonLevel().then(data => {
      let data = [
        {
          "id": 1,
          "levelName": "超级管理员"
        },
        {
          "id": 2,
          "levelName": "单位部门"
        },
      ]
        this.levelList = data;
      //})
    },

    initEditData() {
      if (this.isCreate !== 1) return //不是编辑页，即新增页则直接返回
      const {  roleName, status, level, id } = this.editData
      this.pram.roleName = roleName
      this.pram.status = status
      this.pram.level = level
      this.pram.id = id
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
      });
      //roleApi.getInfo(id).then(res=>{
      let res = {
        "id": 1,
        "roleName": "超级管理员",
        "rules": "admin:dashboard;admin:department;admin:person;admin:electronic;admin:computer;admin:tests;admin:incident;admin:modelType;admin:backups;admin:system;admin:dashboard:list;admin:system:role:list;admin:system:role:save;admin:system:role:update:status;admin:system:role:info;admin:system:role:delete;admin:system:admin:list;admin:system:admin:save;admin:system:admin:update:status;admin:system:admin:info;admin:system:admin:delete;admin:dataConfig;admin:system:category:save;admin:system:category:info;admin:system:category:delete;admin:system:category:update:status;admin:system:category:phone:list;admin:system:category:list;admin:department:delete;admin:department:save;admin:department:info;admin:department:list;admin:system:site:config:info;admin:department:person:list;admin:person:list;admin:person:save;admin:person:info;admin:person:delete;admin:person:import;admin:person:export;admin:electronic:list;admin:electronic:save;admin:electronic:info;admin:electronic:delete;admin:computer:save;admin:computer:list;admin:computer:info;admin:computer:delete;admin:tests:list;admin:tests:save;admin:tests:info;admin:tests:delete;admin:model:type:list;admin:model:type:save;admin:model:type:info;admin:model:type:delete;admin:incident:list;admin:incident:save;admin:incident:info;admin:incident:delete;admin:backups:list;admin:backups:save;admin:backups:restore;admin:backups:down;admin:backups:delete;admin:person:train:list;admin:person:train:save;admin:person:train:info;admin:person:train:delete;admin:maintain;admin:system:attachment:list;admin:system:attachment:download;admin:system:attachment:upload;admin:system:attachment:delete;admin:department:update:status;admin:system:category:phone:insert;admin:system:category:phone:update;admin:system:category:phone:delete;admin:system:category:phone:status;admin:person:material:list;admin:person:material:upload;admin:person:material:download;admin:person:material:delete;admin:electronic:account:list;admin:electronic:account:save;admin:electronic:account:info;admin:electronic:account:delete;admin:workshop;admin:workshop:list;admin:workshop:save;admin:workshop:info;admin:workshop:delete;admin:system:attachment:move;admin:department:person:order;admin:message;admin:message:list;admin:message:info;admin:protection:point;admin:protection:point:list;admin:protection:point:save;admin:protection:point:info;admin:protection:point:delete;admin:person:material:move;admin:tests:export;admin:workshop:export",
        "level": 1,
        "status": 1,
        "menuList": [
          {
            "id": 1,
            "pid": 0,
            "name": "首页",
            "icon": "s-home",
            "component": "/dashboard",
            "perms": "admin:dashboard:list",
            "menuType": "M",
            "url": "",
            "sort": 1,
            "isShow": 1,
            "checked": true,
            "childList": []
          },
          {
            "id": 2,
            "pid": 0,
            "name": "通讯录管理",
            "icon": "office-building",
            "component": "/address/index",
            "perms": "admin:address:list",
            "menuType": "M",
            "url": "",
            "sort": 2,
            "isShow": 1,
            "checked": true,
            "childList": []
          },
          {
            "id": 3,
            "pid": 0,
            "name": "通知公告",
            "icon": "menu",
            "component": "/notice/index",
            "perms": "admin:notice:list",
            "menuType": "M",
            "url": "",
            "sort": 3,
            "isShow": 1,
            "checked": false,
            "childList": []
          },
          {
            "id": 4,
            "pid": 0,
            "name": "求职需求信息库管理",
            "icon": "camera",
            "component": "/jobRequire/index",
            "perms": "admin:job:require:list",
            "menuType": "M",
            "url": "",
            "sort": 4,
            "isShow": 1,
            "checked": false,
            "childList": []
          },
          {
            "id": 5,
            "pid": 0,
            "name": "招聘岗位信息库",
            "icon": "user-solid",
            "component": "/position/index",
            "perms": "admin:position:list",
            "menuType": "M",
            "url": "",
            "sort": 5,
            "isShow": 1,
            "checked": false,
            "childList": []
          },
          {
            "id": 6,
            "pid": 0,
            "name": "创业担保贷款信息库",
            "icon": "user-solid",
            "component": "/loan/index",
            "perms": "admin:loan:list",
            "menuType": "M",
            "url": "",
            "sort": 5,
            "isShow": 1,
            "checked": false,
            "childList": []
          },
          /*{
            "id": 110,
            "pid": 0,
            "name": "消息通知",
            "icon": "bell",
            "component": "/message",
            "perms": "admin:message",
            "menuType": "M",
            "url": "",
            "sort": 11,
            "isShow": 1,
            "checked": false,
            "childList": [
              {
                "id": 111,
                "pid": 110,
                "name": "消息列表",
                "icon": "",
                "component": "/message/index",
                "perms": "admin:message:list",
                "menuType": "C",
                "url": "/api/message/getMessageList",
                "sort": 0,
                "isShow": 1,
                "checked": false,
              },
           {
                "id": 111,
                "pid": 110,
                "name": "消息列表",
                "icon": "",
                "component": "/message/index",
                "perms": "admin:message:list",
                "menuType": "C",
                "url": "/api/message/getMessageList",
                "sort": 0,
                "isShow": 1,
                "checked": false
              }
            ]
          },
          {
            "id": 9,
            "pid": 0,
            "name": "数据管理",
            "icon": "coin",
            "component": "/backups",
            "perms": "admin:backups",
            "menuType": "M",
            "url": "",
            "sort": 12,
            "isShow": 1,
            "checked": false,
            "childList": [
              {
                "id": 70,
                "pid": 9,
                "name": "备份列表",
                "icon": "",
                "component": "/backups/index",
                "perms": "admin:backups:list",
                "menuType": "C",
                "url": "/api/system/backupsList",
                "sort": 0,
                "isShow": 1,
                "checked": false
              }
            ]
          },*/
          {
            "id": 10,
            "pid": 0,
            "name": "系统设置",
            "icon": "setting",
            "component": "/operation",
            "perms": "admin:system",
            "menuType": "M",
            "url": "",
            "sort": 13,
            "isShow": 1,
            "checked": false,
            "childList": [
              {
                "id": 22,
                "pid": 10,
                "name": "公用数据配置",
                "icon": "",
                "component": "/operation/dataConfig",
                "perms": "admin:dataConfig",
                "menuType": "M",
                "url": "",
                "sort": 0,
                "isShow": 1,
                "checked": false,
              },
              {
                "id": 17,
                "pid": 10,
                "name": "管理员列表",
                "icon": "",
                "component": "/operation/adminList",
                "perms": "admin:system:admin:list",
                "menuType": "C",
                "url": "",
                "sort": 0,
                "isShow": 1,
                "checked": false
              },
              {
                "id": 12,
                "pid": 10,
                "name": "角色管理",
                "icon": "",
                "component": "/operation/identityManager",
                "perms": "admin:system:role:list",
                "menuType": "C",
                "url": "",
                "sort": 0,
                "isShow": 1,
                "checked": false
              }
            ]
          },
          {
            "id": 79,
            "pid": 0,
            "name": "维护",
            "icon": "s-open",
            "component": "/maintain/picture",
            "perms": "admin:maintain",
            "menuType": "M",
            "url": "",
            "sort": 14,
            "isShow": 1,
            "checked": false,
            "childList": [
              {
                "id": 80,
                "pid": 79,
                "name": "文件库",
                "icon": "",
                "component": "/maintain/picture",
                "perms": "admin:system:attachment:list",
                "menuType": "C",
                "url": "/api/getAttachmentList",
                "sort": 0,
                "isShow": 1,
                "checked": false
              }
            ]
          }
        ]
      }
      //后期接口调用
        this.menuOptions = res.menuList;
        this.checkDisabled(this.menuOptions);
        loading.close();
        this.getTreeId(res.menuList)
        this.$nextTick(()=>{
          this.menuIds.forEach((i,n) =>{
            var node = this.$refs.menu.getNode(i);
            if(node.isLeaf){
              this.$refs.menu.setChecked(node, true);
            }
          })
        })
      //})
    },
    handlerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid) return
        let roles = this.getMenuAllCheckedKeys().toString();
        this.pram.rules = roles;
        if (this.isCreate === 0) {
          this.handlerSave()
        } else {
          this.handlerEdit()
        }
      })
    }),
    handlerSave() {
      //console.log(this.pram);return false;
      //roleApi.addRole(this.pram).then(data => {
        this.$message.success('创建身份成功')
        this.$emit('hideEditDialog')
      //})
    },
    handlerEdit() {
      //roleApi.addRole(this.pram).then(data => {
        this.$message.success('更新身份成功')
        this.$emit('hideEditDialog')
      //})
    },
    rulesSelect(selectKeys) {
      this.pram.rules = selectKeys
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.menuCheckStrictly = value ? true: false;
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    getCacheMenu(){
      if (this.isCreate !== 0) return ////不是新增页，即编辑页则直接返回

      const loading = this.$loading({
        lock: true,
        text: 'Loading',
      });
      //roleApi.permissionTree().then(res=>{
      let res = [
        {
          "id": 1,
          "pid": 0,
          "name": "首页",
          "icon": "s-home",
          "component": "/dashboard",
          "perms": "admin:dashboard:list",
          "menuType": "M",
          "url": "",
          "sort": 1,
          "isShow": 1,
          "checked": false,
          "childList": []
        },
        {
          "id": 2,
          "pid": 0,
          "name": "通讯录管理",
          "icon": "office-building",
          "component": "/address/index",
          "perms": "admin:address:list",
          "menuType": "M",
          "url": "",
          "sort": 2,
          "isShow": 1,
          "checked": false,
          "childList": []
        },
        {
          "id": 3,
          "pid": 0,
          "name": "通知公告",
          "icon": "menu",
          "component": "/notice/index",
          "perms": "admin:notice:list",
          "menuType": "M",
          "url": "",
          "sort": 3,
          "isShow": 1,
          "checked": false,
          "childList": []
        },
        {
          "id": 4,
          "pid": 0,
          "name": "求职需求信息库管理",
          "icon": "camera",
          "component": "/jobRequire/index",
          "perms": "admin:job:require:list",
          "menuType": "M",
          "url": "",
          "sort": 4,
          "isShow": 1,
          "checked": false,
          "childList": []
        },
        {
          "id": 5,
          "pid": 0,
          "name": "招聘岗位信息库",
          "icon": "user-solid",
          "component": "/position/index",
          "perms": "admin:position:list",
          "menuType": "M",
          "url": "",
          "sort": 5,
          "isShow": 1,
          "checked": false,
          "childList": []
        },
        {
          "id": 6,
          "pid": 0,
          "name": "创业担保贷款信息库",
          "icon": "user-solid",
          "component": "/loan/index",
          "perms": "admin:loan:list",
          "menuType": "M",
          "url": "",
          "sort": 5,
          "isShow": 1,
          "checked": false,
          "childList": []
        },
        /*{
          "id": 110,
          "pid": 0,
          "name": "消息通知",
          "icon": "bell",
          "component": "/message",
          "perms": "admin:message",
          "menuType": "M",
          "url": "",
          "sort": 11,
          "isShow": 1,
          "checked": false,
          "childList": [
            {
              "id": 111,
              "pid": 110,
              "name": "消息列表",
              "icon": "",
              "component": "/message/index",
              "perms": "admin:message:list",
              "menuType": "C",
              "url": "/api/message/getMessageList",
              "sort": 0,
              "isShow": 1,
              "checked": false
            }
          ]
        },
        {
          "id": 9,
          "pid": 0,
          "name": "数据管理",
          "icon": "coin",
          "component": "/backups",
          "perms": "admin:backups",
          "menuType": "M",
          "url": "",
          "sort": 12,
          "isShow": 1,
          "checked": false,
          "childList": [
            {
              "id": 70,
              "pid": 9,
              "name": "备份列表",
              "icon": "",
              "component": "/backups/index",
              "perms": "admin:backups:list",
              "menuType": "C",
              "url": "/api/system/backupsList",
              "sort": 0,
              "isShow": 1,
              "checked": false
            }
          ]
        },*/
        {
          "id": 10,
          "pid": 0,
          "name": "系统设置",
          "icon": "setting",
          "component": "/operation",
          "perms": "admin:system",
          "menuType": "M",
          "url": "",
          "sort": 13,
          "isShow": 1,
          "checked": false,
          "childList": [
            {
              "id": 38,
              "pid": 10,
              "name": "随手拍提示配置",
              "icon": "",
              "component": "/operation/tipsConfig",
              "perms": "admin:system:tips:config:info",
              "menuType": "C",
              "url": "",
              "sort": 0,
              "isShow": 1,
              "checked": false
            },
            {
              "id": 39,
              "pid": 10,
              "name": "奖励配置",
              "icon": "",
              "component": "/operation/rewardConfig",
              "perms": "admin:system:reward:config:info",
              "menuType": "C",
              "url": "",
              "sort": 0,
              "isShow": 1,
              "checked": false
            },
            {
              "id": 22,
              "pid": 10,
              "name": "公用数据配置",
              "icon": "",
              "component": "/operation/dataConfig",
              "perms": "admin:dataConfig",
              "menuType": "M",
              "url": "",
              "sort": 0,
              "isShow": 1,
              "checked": false,
            },
            {
              "id": 17,
              "pid": 10,
              "name": "管理员列表",
              "icon": "",
              "component": "/operation/adminList",
              "perms": "admin:system:admin:list",
              "menuType": "C",
              "url": "/api/getUserList",
              "sort": 0,
              "isShow": 1,
              "checked": false
            },
            {
              "id": 12,
              "pid": 10,
              "name": "角色管理",
              "icon": "",
              "component": "/operation/identityManager",
              "perms": "admin:system:role:list",
              "menuType": "C",
              "url": "/api/role/getRoleList",
              "sort": 0,
              "isShow": 1,
              "checked": false
            }
          ]
        },
        {
          "id": 79,
          "pid": 0,
          "name": "维护",
          "icon": "s-open",
          "component": "/maintain/picture",
          "perms": "admin:maintain",
          "menuType": "M",
          "url": "",
          "sort": 14,
          "isShow": 1,
          "checked": false,
          "childList": [
            {
              "id": 80,
              "pid": 79,
              "name": "文件库",
              "icon": "",
              "component": "/maintain/picture",
              "perms": "admin:system:attachment:list",
              "menuType": "C",
              "url": "/api/getAttachmentList",
              "sort": 0,
              "isShow": 1,
              "checked": false
            }
          ]
        }
      ]
        this.menuOptions = res;
        this.checkDisabled(this.menuOptions);
        loading.close();
      //})
    },
    getTreeId(datas) {
      for(var i in datas){
        if(datas[i].checked) this.menuIds.push(datas[i].id)
        if(datas[i].childList){
          this.getTreeId(datas[i].childList);
        }
      }
    },
    checkDisabled(data){
      return

      //设置公共权限默认勾选且不可操作
      data.forEach(item=>{
        if(item.id === 10 || item.id === 79){
          item.disabled = true;
          item.childList.forEach(item1=>{
            item1.disabled = true;
            this.$nextTick(()=>{
              var node = this.$refs.menu.getNode(item1.id);
              if(node.isLeaf){
                this.$refs.menu.setChecked(node, true);
              }
            })
            if(item1.childList){
              item1.childList.forEach(item2=>{
                item2.disabled = true;
                this.$nextTick(()=>{
                  var node2 = this.$refs.menu.getNode(item2.id);
                  if(node2.isLeaf){
                    this.$refs.menu.setChecked(node2, true);
                  }
                })
                if(item2.childList){
                  item2.childList.forEach(item3=>{
                    item3.disabled = true;
                    this.$nextTick(()=>{
                      var node3 = this.$refs.menu.getNode(item3.id);
                      if(node3.isLeaf){
                        this.$refs.menu.setChecked(node3, true);
                      }
                    })
                  })
                }
              })
            }

          })
        }
      })
    },
  }
}
</script>

<style scoped>

</style>
